/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.google.gson.Gson;
import conexion.JsonFormat;
import conexion.SqlFormat;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.json.JsonArray;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import libreriaTicket.dao.DaoComuna;
import libreriaTicket.dao.DaoUsuario;
import libreriaTicket.entity.Comuna;
import libreriaTicket.entity.Region;
import libreriaTicket.entity.Usuario;

/**
 *
 * @author Moises sepulveda
 */
public class User extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*response.setContentType("text/html;charset=UTF-8");
         PrintWriter out = response.getWriter();
         */
        try {
            /* TODO output your page here. You may use following sample code. */
            /* out.println("<!DOCTYPE html>");
             out.println("<html>");
             out.println("<head>");
             out.println("<title>Servlet User</title>");            
             out.println("</head>");
             out.println("<body>");
             out.println("<h1>Servlet User at " + request.getContextPath() + "</h1>");
             out.println("</body>");
             out.println("</html>");*/
        } finally {
            /*out.close();*/
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        //---Se recupera la accion
       /* int accion = Integer.parseInt(request.getParameter("accion"));*/

        /*response.setContentType("application/json");
         PrintWriter out = response.getWriter();*/

        int accion = Integer.parseInt(request.getParameter("accion"));

        if (accion == 10) {
            getComunas(request, response);
        }

        if (accion == SqlFormat.INSERTAR) {
            insertarUsuario(request, response);
        }
        if (accion == SqlFormat.SELECCIONAR) {
            getUsuarios(request, response);
        }

        //---En caso de que se requiera las comunas por region



    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void getComunas(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        //--Se recuperan las comuans por region
        ArrayList<Comuna> comunas = DaoComuna.sqlComunasByRegion(
                new Region(Integer.parseInt(request.getParameter("idRegion"))));

        //--se devuelve el json
        Gson json = new Gson();

        out.write(json.toJson(comunas));


    }

    public void insertarUsuario(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        //--Se recuperan las comuans por region
        Usuario usuario = new Usuario();
        usuario.setRut(Integer.parseInt(request.getParameter("rut")));
        usuario.setDv(request.getParameter("dv").charAt(0));
        usuario.setPassword(request.getParameter("password"));
        usuario.setApellidoPaterno(request.getParameter("apellidoPaterno"));
        usuario.setApellidoMaterno(request.getParameter("apellidoMaterno"));
        usuario.setDireccion(request.getParameter("direccion"));
        usuario.setUsuario(request.getParameter("usuario"));
        usuario.setComuna(new Comuna(Integer.parseInt(request.getParameter("comuna"))));

        //--se devuelve el json
        JsonFormat json = new JsonFormat();
        if (DaoUsuario.sqlInsert(usuario)) {
            json.addField("codigo", 1);
        } else {
            json.addField("codigo", 0);
        }
        
        out.write(json.getJsonSentence());

    }

    public void getUsuarios(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        //--Se recuperan las comuans por region
        ArrayList<Usuario> usuarios = DaoUsuario.sqlSelectAll();

        //--se devuelve el json
        Gson json = new Gson();

        out.write(json.toJson(usuarios));


    }
}
